package com.handong.handserialprogram.thread;

import android.os.Process;
import android.text.TextUtils;

import com.handong.handserialprogram.constants.HttpConstant;
import com.handong.handserialprogram.model.status.MissionOverResponse;
import com.handong.handserialprogram.utils.EventBusUtil;
import com.handong.handserialprogram.utils.JLog;
import com.handong.handserialprogram.utils.MinaUtil;
import com.handong.handserialprogram.utils.SPUtil;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Arrays;

/**
 * Created by userKey on 2017/8/16.
 */

public class FinMissRunnable implements Runnable {

    private static final String TAG = FinMissRunnable.class.getSimpleName();

    private NioSocketConnector mConnector;
    private IoSession mSession;

    private byte[] mUploadBuff;
    private int mWaitCount = 0;
    private int mFailCount = 0;

    private boolean mIsWorking = true;
    private boolean mIsSendSuccess = false;
    private boolean mIsConnectedSuccess = false;
    private boolean isClearAlert=false;

    public FinMissRunnable(byte[] uploadBuff) {
        this.mUploadBuff = uploadBuff;
    }



    @Override
    public void run() {
        //设置为后台线程 避免与main线程争夺资源。
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        while (mIsWorking) {
            try {

                if (mWaitCount == 12) {
                    clearAlert();
                    EventBusUtil.post(new MissionOverResponse(MissionOverResponse.OVER_TIME_OUT));
                    break;
                }

                if (mFailCount == -5) {
                    EventBusUtil.post(new MissionOverResponse(MissionOverResponse.OVER_ERROR));
                    break;
                }
                uploadWarningInformation();


            } catch (Exception e) {
                e.printStackTrace();
                mFailCount--;
            }
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                break;
            }
            if (!mIsWorking) {
                break;
            }
        }
        closeMinaSocket();
        out(Thread.currentThread().getId() + "upload has been destroyed.");
    }

    /**
     * 删除提示信息。
     */
    private void clearAlert() throws Exception {
        initeConnectionClear();

            if (mSession != null && mSession.isConnected()) {
                if (!mIsConnectedSuccess) {
                    Thread.sleep(1500);
                    mIsConnectedSuccess = true;
                }
                 mUploadBuff[1]= HttpConstant.CLEAR_ALERT_BYTE;
                IoBuffer buffer = IoBuffer.wrap(mUploadBuff);
                mSession.write(buffer);
                mIsSendSuccess = true;
                closeMinaSocket();
                out(" upload Fin request success.");
            }
    }

    /**
     * 上传警告信息。
     */
    private void uploadWarningInformation() throws Exception {

        initConnection();

        if (!mIsSendSuccess) {
            if (mSession != null && mSession.isConnected()) {
                if (!mIsConnectedSuccess) {
                    Thread.sleep(1500);
                    mIsConnectedSuccess = true;
                }
                IoBuffer buffer = IoBuffer.wrap(mUploadBuff);
                mSession.write(buffer);
                mIsSendSuccess = true;
                EventBusUtil.post(new MissionOverResponse(MissionOverResponse.OVER_RESPONSE));
                closeMinaSocket();
                out(" upload Fin request success.");
            }
        } else {
            out("等待服务端同意结束任务！");
            mWaitCount++;
        }
    }

//    /**
//     * 上传警告信息。
//     */
//    private void sendNoInformation() throws Exception {
//
//        initConnection();
//
//        if (!mIsSendSuccess) {
//            if (mSession != null && mSession.isConnected()) {
//                if (!mIsConnectedSuccess) {
//                    Thread.sleep(1500);
//                    mIsConnectedSuccess = true;
//                }
//                IoBuffer buffer = IoBuffer.wrap(mUploadBuff);
//                mSession.write(buffer);
//                mIsSendSuccess = true;
//                //EventBusUtil.post(new MissionOverResponse(MissionOverResponse.OVER_RESPONSE));
//                closeMinaSocket();
//                out(" upload Fin request success.");
//            }
//        } else {
//            out("等待服务端同意结束任务！");
//            mWaitCount++;
//        }
//    }

    private void initeConnectionClear() throws Exception {

        if (mConnector == null) {
            out("客户端开始链接");
            mConnector = new NioSocketConnector();
            mConnector.setConnectTimeoutMillis(3000);
            mConnector.getFilterChain().addLast(
                    "codec",
                    new ProtocolCodecFilter(new TextLineCodecFactory(Charset
                            .forName("UTF-8"),
                            LineDelimiter.WINDOWS.getValue(),
                            LineDelimiter.WINDOWS.getValue())));
            mConnector.setHandler(new MinaClientHandler() {

                @Override
                public void messageReceived(IoSession session, Object message) throws Exception {
                    super.messageReceived(session, message);
                    IoBuffer ioBuffer = (IoBuffer) message;
                    String response = MinaUtil.ioBufferToString(ioBuffer);
                    if (TextUtils.isEmpty(response)) {
                        return;
                    }
                    String[] child = response.split("&");
                    if (child.length < 3) {
                        return;
                    }

                    out(Arrays.toString(child));
                }
            });
            String ip = SPUtil.getStringValue(SPUtil.SERVER_IP);
            int port = SPUtil.getIntValue(SPUtil.UPLOAD_PORT);
            //String ip = "10.1.200.95";
            //int port = 9503;
            mConnector.setDefaultRemoteAddress(new InetSocketAddress(
                    ip, port));

            mConnector.addListener(new IoListener() {

                @Override
                public void sessionDestroyed(IoSession arg0) throws Exception {
                    super.sessionDestroyed(arg0);
                    mSession = null;
                    mIsConnectedSuccess = false;
                }
            });
        }

        if (mSession == null) {
            ConnectFuture future = mConnector.connect();
            future.awaitUninterruptibly();// 等待连接创建完成
            mSession = future.getSession();
        }
    }

    private void initConnection() throws Exception {
        if (mIsSendSuccess) {
            return;
        }
        if (mConnector == null) {
            out("客户端开始链接");
            mConnector = new NioSocketConnector();
            mConnector.setConnectTimeoutMillis(3000);
            mConnector.getFilterChain().addLast(
                    "codec",
                    new ProtocolCodecFilter(new TextLineCodecFactory(Charset
                            .forName("UTF-8"),
                            LineDelimiter.WINDOWS.getValue(),
                            LineDelimiter.WINDOWS.getValue())));
            mConnector.setHandler(new MinaClientHandler() {

                @Override
                public void messageReceived(IoSession session, Object message) throws Exception {
                    super.messageReceived(session, message);
                    IoBuffer ioBuffer = (IoBuffer) message;
                    String response = MinaUtil.ioBufferToString(ioBuffer);
                    if (TextUtils.isEmpty(response)) {
                        return;
                    }
                    String[] child = response.split("&");
                    if (child.length < 3) {
                        return;
                    }

                    out(Arrays.toString(child));
                }
            });
            String ip = SPUtil.getStringValue(SPUtil.SERVER_IP);
            int port = SPUtil.getIntValue(SPUtil.UPLOAD_PORT);
            //String ip = "10.1.200.95";
            //int port = 9503;
            mConnector.setDefaultRemoteAddress(new InetSocketAddress(
                    ip, port));

            mConnector.addListener(new IoListener() {

                @Override
                public void sessionDestroyed(IoSession arg0) throws Exception {
                    super.sessionDestroyed(arg0);
                    mSession = null;
                    mIsConnectedSuccess = false;
                }
            });
        }

        if (mSession == null) {
            ConnectFuture future = mConnector.connect();
            future.awaitUninterruptibly();// 等待连接创建完成
            mSession = future.getSession();
        }
    }

    public void destroy() {
        mIsWorking = false;
    }

    public void closeMinaSocket() {

        if (mSession != null) {
            mSession.closeNow();
            //mSession.getCloseFuture().awaitUninterruptibly(1000);
            mSession = null;
        }

        if (mConnector != null) {
            mConnector.dispose();
            mConnector = null;
        }
    }

    public static void out(String s) {
        JLog.d(TAG, s);
    }
}
